.PHONY: help build pypkg clean install archive docs docs_require pkg_dir rpm_require srpm rpm

CWD=$(shell pwd)
PYTHON ?= python3
LN ?= ln
SED ?= sed
INSTALL ?= install -p
DESTDIR ?= /

PKGNAME = excavator
VERSION = $(shell cat excavator/VERSION)
PACKAGING_DIR := "packaging"
SERVICE = excavator.service
UNITDIR=$(shell rpm --eval %{_unitdir})
TARGET_WANTSDIR=$(UNITDIR)/excavator.target.wants
GENFILES = excavator.spec


help:
	@echo "Please use 'make <target>' where <target> is one of"
	@echo "  help       show help text"
	@echo "  docs       make excavator docs"
	@echo "             docs index.html path is (docs/_build/html/index.html) "
	@echo "  install    install excavator in local os"
	@echo "  pypkg      build python archive"
	@echo "  clean      clean code dir"
	@echo "  archive    make tar.gz archive"
	@echo "             archive path is (packaging/) "
	@echo "  srpm       make srpm pkg"
	@echo "             srpm path is (packaging/SRPM) "
	@echo "  rpm        make rpm pkg"
	@echo "             rpm path is (packaging/RPM) "

$(GENFILES): %: %.in
	$(SED) -e 's,@VERSION@,$(VERSION),g' \
		$< > $@

build:
	$(PYTHON) setup.py build

install: build
	$(PYTHON) setup.py install --root=$(DESTDIR)
	$(INSTALL) -d $(DESTDIR)$(TARGET_WANTSDIR)
	$(LN) -sf ../$(SERVICE) $(DESTDIR)$(TARGET_WANTSDIR)/$(SERVICE)


pypkg:
	$(PYTHON) setup.py sdist

clean:
	@ echo "clean"
	-@rm -rf build/ dist/ *.egg-info
	-@find . -name '__pycache__' -exec rm -fr {} +
	-@find . -name '*.pyc' -exec rm -f {} +
	-@find . -name '*.pyo' -exec rm -f {} +
	-@find . -name 'SERVER_LOGS_FILE' -exec rm -f {} +
#	-@rm -rf docs/_build



docs_require: requirements_docs.txt
	@ echo "download docs requires"
	@ pip3 install -r requirements_docs.txt

docs: docs_require
	@ echo "docs"
	@ $(MAKE) -C docs html

pkg_dir:
	@ echo "crate pkg dir"
	@ mkdir -p $(PACKAGING_DIR)

archive: pkg_dir
	@git archive --prefix "$(PKGNAME)-$(VERSION)/" -o "$(PACKAGING_DIR)/$(PKGNAME)-$(VERSION).tar.gz" HEAD
	@echo "The archive is in $(PACKAGING_DIR)/$(PKGNAME)-$(VERSION).tar.gz"

rpm_require: ${PKGNAME}.spec
	@ echo "download rpm build tools"
	@ dnf install rpm-build -y
	@ echo "download rpm buildrequires"
	@ dnf builddep excavator.spec -y

srpm: archive rpm_require
	@ echo "build srpm"
	@ rpmbuild -bs ${PKGNAME}.spec \
  		--define "_specdir $(CWD)/" \
		--define "_sourcedir $(CWD)/$(PACKAGING_DIR)/" \
		--define "_srcrpmdir $(CWD)/$(PACKAGING_DIR)/SRPMS" \
		--define "_builddir $(CWD)/$(PACKAGING_DIR)/BUILD" \
		--define "_buildrootdir $(CWD)/$(PACKAGING_DIR)/BUILDROOT" \
		--define "_rpmdir $(CWD)/$(PACKAGING_DIR)/RPMS"

rpm: archive rpm_require
	@ echo "build rpm"
	@ rpmbuild -ba ${PKGNAME}.spec \
		--define "_specdir $(CWD)/" \
		--define "_sourcedir $(CWD)/$(PACKAGING_DIR)/" \
		--define "_srcrpmdir $(CWD)/$(PACKAGING_DIR)/SRPMS" \
		--define "_builddir $(CWD)/$(PACKAGING_DIR)/BUILD" \
		--define "_buildrootdir $(CWD)/$(PACKAGING_DIR)/BUILDROOT" \
		--define "_rpmdir $(CWD)/$(PACKAGING_DIR)/RPMS"